package com.box.controller;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.box.entity.*;
import com.box.service.*;
import org.apache.ibatis.annotations.Param;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.box.utils.SessionUtils;
import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.javabeans.qzone.UserInfoBean;
import com.qq.connect.oauth.Oauth;

@Controller
public class PageController {

	private Logger log=Logger.getLogger(PageController.class);

	@Autowired 
	private AdminService adminService;
	
	@Autowired
	private WebService webService;
	
	
	@Autowired
	private LinkService linkService;
	
	@Autowired
	private BlogTypeService blogTypeService;
	
	@Autowired
	private BlogService blogService;
	
	@Autowired
	private AdviceService noticeService;
	
	@Autowired
	private ThemeService themeService;
	
	@Autowired
	private PersonInfoService personService;
	
	@Autowired
	private AdviceService adviceServcice;
	
	@Autowired
	private ArticleTypeService ArticleTypeService;
	
	@Autowired
	private ArticleService articleService;

	@Autowired
	private TemplateService templateService;

	
	@Value("${TYPEID}")
	private String TYPEID;
	 
	@Value("${ARTICLETYPEID}")
	private String ARTICLETYPEID;

	@Autowired
	private ArticleAndArticleTypeService articleAndArticleTypeService;

	/**
	 * 打开首页
	 */
	@RequestMapping("/")
	public String showIndex() {
	
		return "index";
	}
	

	/**
	 * 展示其他页面
	 * <p>Title: showpage</p>
	 * <p>Description: </p>
	 * @param page
	 * @return
	 */
	@RequestMapping("/{page}")
	public String showpage(@RequestParam(value="typeId",defaultValue="1",required=false) String typeId,@RequestParam(value="arid",defaultValue="1",required=false) String arid,@RequestParam(value="artypeid",defaultValue="1",required=false) String artypeid,@PathVariable String page,@RequestParam(value="tid",defaultValue="1",required=false) String tid,@RequestParam(value="id",defaultValue="1",required=false) String id,@RequestParam(value="advid",defaultValue="1",required=false) String advid,@RequestParam(value = "templateId",required = false,defaultValue = "1") Integer templateId,Model model) {
		SessionUtils.setSessionAttribute(TYPEID, typeId);
		log.debug(TYPEID+"...................属性文件中的TYPEID");
		SessionUtils.setSessionAttribute(ARTICLETYPEID, artypeid);
		DbWeb web = webService.selWebByOne(2);
		log.debug(web);
		model.addAttribute("web", web);
		List<DbLink> link = linkService.selLinks();
		model.addAttribute("link", link);
		log.debug(page+"前端页面");
		//专题
		List<DbBtype> type = blogTypeService.selBlogTypeList();
		model.addAttribute("types",type);
		log.debug(tid+".................首页tid");
		
		try {
			List<DbBlog> selBlogList = blogService.selBlogList();
			model.addAttribute("headline", selBlogList);
			List<DbBlog> selBlogByType = blogService.selBlogByType(Integer.parseInt(tid));
			model.addAttribute("blogbytypeid", selBlogByType);
			List<DbBlog> selBlogByTypes = blogService.selBlogByType(Integer.parseInt(tid));
			model.addAttribute("blogbytypeids", selBlogByTypes);
			//网站公告
			List<DbAdvice> notice = noticeService.selAdviceList();
			model.addAttribute("notice", notice);
			//首页轮播图
			List<DbTheme> theme = themeService.selTheme(1);
			model.addAttribute("theme", theme);
			//博客列表+阅读次数增加
			 BlogTypeEntity blog = blogService.selBlogById(Integer.parseInt(id));
			model.addAttribute("blog", blog);
		
			
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		//点击排行
		List<DbBlog> list = blogService.selBlogListByClickHit();
		model.addAttribute("blogclick", list);
		//站长推荐
		List<DbBlog> replyHit = blogService.selBlogListByReplyId();
		model.addAttribute("replyHit", replyHit);
		//个人博客日记专栏
		DbPersonInfo person = personService.selPersonInfoById("1");
		model.addAttribute("person", person);
		//猜猜你喜欢模块
		List<DbBlog> guess= blogService.selBlogListByGuess();
		model.addAttribute("guess", guess);
		//根据博客类型id进行查询对应的数据记录
		DbBtype selBlogTypeById = blogTypeService.selBlogTypeById(Integer.parseInt(typeId));
		model.addAttribute("blogtype", selBlogTypeById);
		////首页广告以下根据广告uppid进行查询对应广告,基本广告uppid定死只修改内容
		DbTheme ad1 = themeService.selThemeByUppid(201);//首页中间广告
		model.addAttribute("ad1", ad1);
		DbTheme ad2 = themeService.selThemeByUppid(202);//首页右侧上面广告
		model.addAttribute("ad2", ad2);
		DbTheme ad3 = themeService.selThemeByUppid(203);
		model.addAttribute("ad3", ad3);
		//博客列表中的广告
		DbTheme ad4 = themeService.selThemeByUppid(301);
		model.addAttribute("ad4", ad4);
		DbTheme ad5 = themeService.selThemeByUppid(302);
		model.addAttribute("ad5", ad5);
		//个人博客日记中的广告
		DbTheme ad6 = themeService.selThemeByUppid(401);
		model.addAttribute("ad6", ad6);
		DbTheme ad7 = themeService.selThemeByUppid(402);
		model.addAttribute("ad7", ad7);
		//文章列表中的广告
		DbTheme ad8 = themeService.selThemeByUppid(501);
		model.addAttribute("ad8", ad8);
		DbTheme ad9 = themeService.selThemeByUppid(502);
		model.addAttribute("ad9", ad9);
		//博客内容中间的广告
		DbTheme ad10 = themeService.selThemeByUppid(602);
		model.addAttribute("ad10", ad10);
		DbTheme ad11= themeService.selThemeByUppid(603);
		model.addAttribute("ad11", ad11);
		DbTheme ad12 = themeService.selThemeByUppid(604);
		model.addAttribute("ad12", ad12);
		//公告内容页面中的广告
		DbTheme ad13 = themeService.selThemeByUppid(701);
		model.addAttribute("ad13", ad13);
		DbTheme ad14= themeService.selThemeByUppid(702);
		model.addAttribute("ad14", ad14);
		DbTheme ad15= themeService.selThemeByUppid(703);
		model.addAttribute("ad15", ad15);
		//文章分类列表广告
		DbTheme ad16 = themeService.selThemeByUppid(801);
		model.addAttribute("ad16", ad16);
		DbTheme ad17 = themeService.selThemeByUppid(802);
		model.addAttribute("ad17", ad17);
		//阿里云广告
		List<DbTheme> aliList = themeService.selTheme(601);
		model.addAttribute("aliList", aliList);
		//首页新闻模块显示4个板块内容块
		//个人博客板块
		SelBlogAndType blog = blogService. selBlogTypeByTypeId(1);
		DbBtype btype = blog.getBtype();
		model.addAttribute("newstagblogtype",  btype);
		List<DbBlog> bloglist = blog.getBlog();
		model.addAttribute("newstagbloglist", bloglist);
		//韩语学习板块
		SelBlogAndType korean = blogService. selBlogTypeByTypeId(18);
		DbBtype koreanName = korean .getBtype();
		model.addAttribute("koreanName",  koreanName);
		List<DbBlog> konreanList = korean.getBlog();
		model.addAttribute("konreanList" , konreanList );
		//java笔记板块
		SelBlogAndType java= blogService. selBlogTypeByTypeId(2);
		List<DbBlog> javaList= java.getBlog();
		model.addAttribute("javaList",javaList);
		DbBtype javaObjecType = java.getBtype();
		model.addAttribute("javaObjecType", javaObjecType);
		Integer n=Integer.parseInt(typeId);
		
		//php学习板块
		SelBlogAndType php= blogService. selBlogTypeByTypeId(3);
		DbBtype phpObject = php.getBtype();
		model.addAttribute("phpObject", phpObject);
		List<DbBlog> phpObjectList = php.getBlog();
		model.addAttribute("phpObjectList", phpObjectList);
		//心得笔记
		SelBlogAndType heartNote = blogService. selBlogTypeByTypeId(1);
		List<DbBlog> heartBlogList = heartNote.getBlog(); 
		model.addAttribute("heartBlogList", heartBlogList);
		DbBtype heartBType = heartNote.getBtype();
		model.addAttribute("heartBType", heartBType);
		//nginx笔记
		SelBlogAndType nginx = blogService. selBlogTypeByTypeId(8);
		List<DbBlog> nginxBlogList = nginx.getBlog();
		model.addAttribute("nginxBlogList", nginxBlogList);
		DbBtype nginxBType = nginx.getBtype();
		model.addAttribute("nginxBType", nginxBType);
		//html笔记
		SelBlogAndType html  = blogService. selBlogTypeByTypeId(9);
		List<DbBlog> htmlBlogList = html.getBlog();
		model.addAttribute("htmlBlogList", htmlBlogList);
		DbBtype htmlBType = html.getBtype();
		model.addAttribute("htmlBType", htmlBType);
		//公告内容
		DbAdvice advice = adviceServcice.selAdviceDataById(advid);
		model.addAttribute("advice", advice);
		//首页顶部显示文章tab列表
		List<DbArticletype> selArticleTypeById = ArticleTypeService.selArticleTypeById();
		model.addAttribute("articletypes",  selArticleTypeById);
		//文章列表中的类型
		DbArticletype articletype = ArticleTypeService.selTypeByTypeid(Integer.parseInt(artypeid));
		model.addAttribute("articletype", articletype);
		//文章列表加阅读次数增加
		ArticleAndArticleType selObjectByArid = articleService.selObjectByArid(Integer.parseInt(arid));
		model.addAttribute("manytype", selObjectByArid);
		//文章列表四个模块显示
		//科幻日记(类型可更改但是类型id不允许更改)
		QueryResultByArticle query = articleService.selArticleTypeByTypeId(8);
		DbArticletype queryByTypeBy8  = query.getType();
		model.addAttribute("queryByTypeBy8", queryByTypeBy8 );
		List<DbArticle> queryByarticle8 = query.getArticle();
		model.addAttribute("queryByarticle8", queryByarticle8);
		//小说天地
		QueryResultByArticle query2 = articleService.selArticleTypeByTypeId(9);
		DbArticletype queryByArticleBy9  = query2.getType();
		model.addAttribute("queryByArticleBy9", queryByArticleBy9);
		List<DbArticle> queryByArticleListBy9 = query2.getArticle();
		model.addAttribute("queryByArticleListBy9", queryByArticleListBy9);
		//妙笔生花
		QueryResultByArticle queryby10 = articleService.selArticleTypeByTypeId(10);
		DbArticletype queryByArticleBy10 = queryby10. getType();
		model.addAttribute("queryByArticleBy10", queryByArticleBy10);
		List<DbArticle> queryByArticleListBy10 = queryby10.getArticle();
		model.addAttribute("queryByArticleListBy10",queryByArticleListBy10 );
		//神话传说
		QueryResultByArticle queryby11 = articleService.selArticleTypeByTypeId(11);
		DbArticletype querybyarticletype11 = queryby11.getType();
		model.addAttribute("querybyarticletype11", querybyarticletype11);
		List<DbArticle> querybyarticlelisttype11 = queryby11.getArticle();
		model.addAttribute("querybyarticlelisttype11", querybyarticlelisttype11);
		//优秀博客优秀博客
		List<DbLink> superLink = linkService.selLinkByUppid(5);
		model.addAttribute("superLink", superLink);
		//优秀博客站长推荐
		List<DbLink> adminO = linkService.selLinkByAdminUrl(10);
		model.addAttribute("adminObject", adminO);
		//模板列表
        try {
            List<DbTemplates> templates = templateService.getListByCreateTime();
            model.addAttribute("templateList",templates);
            DbTemplates  temp=   templateService.getOneById(templateId);
            model.addAttribute("template",temp);
        }catch (Exception e){
            log.debug("无数据，抛出无数据异常"+e);

        }





		return page;
	}
	
	@RequestMapping("/email/{page}")
	public String showEmailPage(@PathVariable String page) {
		System.out.println(page+"前端页面");
		return "email/"+page;
	}
	
	
	@RequestMapping("/druid/index")
	public String showDruidPage(Model model,HttpServletRequest request){
		System.out.println("前端页面");
		return "druid/index";
	}
	
	@RequestMapping("/page/treeGrid")
	public String getTree(Model model,HttpServletRequest request){
		System.out.println("menuList页面");
		return "menu/menuList";
	}
	

	
	@RequestMapping("/shiro/login")
	public String showBackLoginPage(Model model,HttpServletRequest request){
		System.out.println("login页面");
		DbWeb back = webService.selWebByOne(3);
		model.addAttribute("web", back);
		return "login";
	}
	
	
	@RequestMapping("/roles/page/rolesList")
	public String showRolesPage(Model model,HttpServletRequest request){
		
		return "roles/roleList";
	}
	
	
	@RequestMapping(value="/ajax/main",method={RequestMethod.GET,RequestMethod.POST})
	public String getLittleMessage(Model model){
		
		DbAdmin admin= adminService.getDbAdminItems();
		if(admin!=null){
			model.addAttribute("admin",admin);
			return "main";
		}else{
			return "error/404";
		}
	
		
		
		
	}
	
	

	
	

	
	@RequestMapping("/login")
	public String showLogin() {

		return "login";
	}
	/**
	 * 
	
	* @Title: showqqLogin 
	
	* @Description: QQ第三方登录跳转第三方登录页面带参数跳转
	
	* @param @param request
	* @param @param response
	* @param @throws Exception    设定文件 
	
	* @return void    返回类型 
	
	* @throws
	 */
	@RequestMapping(value="/qqlogin",method={RequestMethod.GET,RequestMethod.POST})
	public void showqqLogin(HttpServletRequest request,HttpServletResponse response) throws Exception{
		  response.setContentType("text/html;charset=utf-8");
	        try {
	            response.sendRedirect(new Oauth().getAuthorizeURL(request));
	        } catch (QQConnectException e) {
	            e.printStackTrace();
	        }
	}
	
	/**
	 * 
	
	* @Title:qqReturn
	
	* @Description: 回调页面跳转
	
	* @param @param request
	* @param @param response
	* @param @throws Exception    设定文件 
	
	* @return void    返回类型 
	
	* @throws
	 */
    @RequestMapping("/qqReturn")
    public void qqReturn(HttpServletRequest request, HttpServletResponse response)throws Exception{
        response.setContentType("text/html; charset=utf-8");
        PrintWriter out = response.getWriter();
        try {
            AccessToken accessTokenObj = (new Oauth()).getAccessTokenByRequest(request);
            String accessToken   = null,
                    openID        = null;
            long tokenExpireIn = 0L;

            if (accessTokenObj.getAccessToken().equals("")) {
//                我们的网站被CSRF攻击了或者用户取消了授权
//                做一些数据统计工作
                System.out.print("没有获取到响应参数");
            } else {
                accessToken = accessTokenObj.getAccessToken();
                tokenExpireIn = accessTokenObj.getExpireIn();

                request.getSession().setAttribute("demo_access_token", accessToken);
                request.getSession().setAttribute("demo_token_expirein", String.valueOf(tokenExpireIn));

                // 利用获取到的accessToken 去获取当前用的openid -------- start
                OpenID openIDObj =  new OpenID(accessToken);
                openID = openIDObj.getUserOpenID();

                out.println("欢迎你，代号为 " + openID + " 的用户!");
                request.getSession().setAttribute("demo_openid", openID);




                UserInfo qzoneUserInfo = new UserInfo(accessToken, openID);
                UserInfoBean userInfoBean = qzoneUserInfo.getUserInfo();
                out.println("<br/>");
                if (userInfoBean.getRet() == 0) {
                    out.println(userInfoBean.getNickname() + "<br/>");
                    out.println(userInfoBean.getGender() + "<br/>");
                    out.println("<image src=" + userInfoBean.getAvatar().getAvatarURL30() + "><br/>");
                    out.println("<image src=" + userInfoBean.getAvatar().getAvatarURL50() + "><br/>");
                    out.println("<image src=" + userInfoBean.getAvatar().getAvatarURL100() + "><br/>");
                } else {
                    out.println("很抱歉，我们没能正确获取到您的信息，原因是： " + userInfoBean.getMsg());
                }

            }
        } catch (QQConnectException e) {
        }
    }
}
